package com.briup.run.service.impl;

import com.briup.run.bean.AccessRecord;
import com.briup.run.dao.AccessRecordMapper;
import com.briup.run.service.AccessRecordService;
import com.briup.run.util.SqlSessionUtil;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: vanse(lc))
 * @Date: 2022/10/11-10-11-11:06
 * @Description：com.briup.run.service.impl
 */
public class AccessRecordServiceImpl implements AccessRecordService {
    @Override
    public Map<String, Long> findAll() {
        SqlSession session = SqlSessionUtil.openSession();
        Map<String,Long> map = new HashMap<>();
        session.select("com.briup.run.dao.AccessRecordMapper.findAll",new ResultHandler<AccessRecord>(){
            @Override
            public void handleResult(ResultContext<? extends AccessRecord> resultContext) {
                AccessRecord accessRecord = resultContext.getResultObject();
                map.put(accessRecord.getIp(),accessRecord.getCount());
            }
        });
        session.close();
        return map;
    }

    @Override
    public void add(Map<String,Long> map) {
        SqlSession session = SqlSessionUtil.batchSqlSession();
            AccessRecordMapper mapper = session.getMapper(AccessRecordMapper.class);
            try {
            int i = 0; // 103
            for (Map.Entry<String, Long> entry : map.entrySet()) {
                mapper.add(new AccessRecord(null,entry.getKey(),entry.getValue()));
                // 每50条提交一次
                if(i % 50 == 0 || i == map.size()){ // 103
                    session.commit();
                    session.flushStatements();
                    session.clearCache();
                }
            }
            i++;  // 56

        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    @Override
    public void truncate() {
        SqlSession session = SqlSessionUtil.openSession();
        AccessRecordMapper mapper = session.getMapper(AccessRecordMapper.class);
        try {
            mapper.truncate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}
